<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadApi"
    name="uploadFile"
    accept=".jpg,.png"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const imageUrl = defineModel({
  type: String,
  default: ''
})

const uploadApi = '/api/file/update'
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.message === 'success') {
    ElMessage({
      type: 'success',
      message: '上传成功'
    })
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
  }
}
const beforeAvatarUpload = (file) => {
  const isImg = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImg) {
    ElMessage.error('上传头像图片只能是 JPG、PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isImg && isLt2M
}

// const handleExceed = () => {}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
